//
// Created by HP on 2025/11/13.
//
#include "../include/Headler.h"

bool sendVerificationEmail(const std::string &email, const std::string &verificationCode) {
    if (RdConnector::getInstance()->exists(email)) {
        std::cout << "Verification code already sent to and can't send to quick" << email << std::endl;
        return false;
    }
    if(EmailSender::getInstance()->sendVerificationCode(email, verificationCode)){
        std::cout << "Verification email sent to " << email << std::endl;
        RdConnector::getInstance()->set(email, verificationCode, 60);
        return true;
    }else{
        std::cout << "Failed to send verification email to " << email << std::endl;
        return false;
    }
}

void sendVerificationEmail(const Request& req, Response& res) {
    std::string email = req.query_param("email");
    // 去除空格
    email.erase(remove(email.begin(), email.end(), ' '), email.end());

    std::cout << "Received email: " << email << std::endl;

    // 1. 邮箱格式错误 → 400 Bad Request
    if (email.empty() || email.find("@") == std::string::npos) {
        res.error(400, "Invalid email address");
        return;
    }

    std::string code = generateVerificationCode();
    // 2. 发送成功 → 200 OK（默认状态码，可省略显式设置）
    if (sendVerificationEmail(email, code)) {
        res.json(R"({"Status":"success","message":"Verification code sent successfully"})");
    }
        // 3. 发送失败（服务器内部错误）→ 500 Internal Server Error
    else {
        res.error(500, "Failed to send verification email");
    }
}

